<template>
  <transition
      name="animate__animated animate__bounce"
      appear
      enter-active-class="animate__pulse"
      leave-active-class="animate__pulse"
  >
    <li>
      <label>
        <input type="checkbox" :checked="todo.completed" @change="handleCheck(todo.id)"/>
        <!--todo身上没有isEdit属性，点击编辑按钮后this.$set()添加一个isEdit属性并初始化为true，就会显示编辑框-->
        <span v-show="!todo.isEdit">{{ todo.name }}</span>
        <!--加入一个编辑框 用来更改todo.name-->
        <input
            type="text"
            v-show="todo.isEdit"
            :value="todo.name"
            @blur="handleBlur(todo,$event)"
            ref="inputName"
        >
      </label>
      <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
      <button class="btn btn-edit" v-show="!todo.isEdit" @click="handleEdit(todo)">编辑</button>
    </li>
  </transition>
</template>

<script>
import pubsub from "pubsub-js";
import 'animate.css';
export default {
  name: "UserItem",
  props:['todo'],
  methods:{
    handleCheck(id){
      this.$bus.$emit('checkTodo',id)
    },
    handleDelete(id){
      if (confirm("确定删除吗?")){
        // this.$bus.$emit('deleteTodo',id)
        pubsub.publish('deleteTodo',id)
      }
    },
    handleEdit(todo){
      //如果todo身上已经有isEdit属性，直接改变属性值为true
      if(todo.hasOwnProperty('isEdit')){
        todo.isEdit = true
      }else {
        //如果没有，则追加一个属性isEdit并初始化为true，这样子就可以直接显示input框
        this.$set(todo,'isEdit',true)
      }
      this.$nextTick(()=>{ //下一次模板更新之后执行此回调
        this.$refs.inputName.focus() //使用ref获取到输入框，调用focus获取焦点
      })
    },
    //输入框失去焦点回调，真正执行修改逻辑
    handleBlur(todo,e){
      todo.isEdit = false
      this.$bus.$emit('updateTodo',todo.id,e.target.value)
    }
  }
}
</script>

<style scoped>
/*开启li悬浮背景色*/
  li:hover{
    background-color: #ddd;
  }
/*开启li悬浮时button显示*/
  li:hover button{
    display: block;
  }
  /*item*/
  li {
    list-style: none;
    height: 36px;
    line-height: 36px;
    padding: 0 5px;
    border-bottom: 1px solid #ddd;
  }

  li label {
    float: left;
    cursor: pointer;
  }

  li label li input {
    vertical-align: middle;
    margin-right: 6px;
    position: relative;
    top: -1px;
  }

  li button {
    float: right;
    display: none;
    margin-top: 3px;
  }

  li:before {
    content: initial;
  }

  li:last-child {
    border-bottom: none;
  }
</style>